import { ref, onMounted, onBeforeUnmount } from "vue";
import { useFloating, autoUpdate, offset, flip, shift } from "@floating-ui/vue";
import _ from "lodash";

const defaultProps = {
  label: "label",
  children: "children",
  icon: "icon",
  cmpnt: "cmpnt",
  props: "props",
  divided: "divided",
};
const getPropsMapping = function (props) {
  return _.merge({}, defaultProps, props);
};
const getMenu = function (item, mappingProps) {
  let menuRef = ref(null);
  let subRef = ref(null);
  let open = ref(false);

  let menu = {
    label: _.get(item, mappingProps.label),
    icon: _.get(item, mappingProps.icon),
    cmpnt: _.get(item, mappingProps.cmpnt),
    props: _.get(item, mappingProps.props),
    divided: _.get(item, mappingProps.divided),
    ref: menuRef,
    subRef: subRef,
    open: open,
    event: bindingEvent(open), //此处还有问题todo
    children: getMenus(item[mappingProps.children] || [], mappingProps),
  };

  const { floatingStyles } = useFloating(menuRef, subRef, {
    placement: "right-start",
    middleware: [offset(0), flip(), shift()],
    whileElementsMounted: autoUpdate,
  });
  menu.childrenStyle = floatingStyles;
  return menu;
};
const getMenus = function (menus, mappingProps) {
  let lst = [];
  _.forEach(menus, (item) => {
    lst.push(getMenu(item, mappingProps));
  });
  return lst;
};

const hideMenu = (root, menu, event) => {
  if (!root || !event || root.contains(event.target)) {
    return;
  }
  menu.open = false;
  if (!menu.children || menu.children.length === 0) {
    return;
  }
  menu.children.forEach((item) => {
    item.open = false;
    hideMenu(root, item.children || [], event);
  });
};

const bindingHideMenu = (root, floating, open) => {
  let clickOutsideHandler = function (event) {
    if (!open.value) {
      return;
    }
    if (
      !root.value.contains(event.target) &&
      !floating.value.contains(event.target)
    ) {
      open.value = false;
    }
  };
  onMounted(() => {
    document.addEventListener("click", clickOutsideHandler);
  });
  onBeforeUnmount(() => {
    document.removeEventListener("click", clickOutsideHandler);
  });
};
var lastOpen = ref(false);
const switchOpen = (open) => {
  if (lastOpen.value) lastOpen.value = false;
  open.value = true;
  lastOpen = open;
};

const bindingEvent = function (open) {
  return {
    click() {
      // open.value = true;
      switchOpen(open);
    },
  };
};
export {
  getMenu,
  getMenus,
  hideMenu,
  getPropsMapping,
  bindingHideMenu,
  bindingEvent,
  switchOpen,
};
